package cn.itcast.cmf.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.cmf.service.CustomerService;
import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findAssociationCustomers(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomerToFixedArea(String fixedAreaId, String customerId) {
		//解除关联'
		customerRepository.clearAssociation(fixedAreaId);
		if (StringUtils.isBlank(customerId) || customerId.equals("null")) {
			return;
		}
		
		String[] ids = customerId.split(",");
		for (String idstr : ids) {
			Integer id = Integer.parseInt(idstr);
			customerRepository.updateToAssociation(fixedAreaId, id);
		}
	}

	@Override
	public void regist(Customer customer) {
		customerRepository.save(customer);
	}

	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		return customerRepository.findFixedAreaByAddress(address);
	}
}
